﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WHLRDF.ORM;
using WHLRDF.Application.Model;
namespace WHLRDF.Application.BLL
{
    public enum PermissionType {
        Role=0,
        Group=1,
        Dept=2,
        User = 3
    }
    public class PermissionService : SerivceBase, IPermissionService
    {

        #region 基本方法
        /// <summary>
        /// 查询所有
        /// </summary>
        public List<PermissionEntity> GetAll()
        {
            ICriterion criter = Expression.Eq(PermissionEntity.__IsDeleted, false);
            return this.Query<PermissionEntity>(criter).ToList();

        }
        /// <summary>
        /// 获取单个实例的方法
        /// <param name="id">object类型</param>
        /// </summary>
        public PermissionEntity GetById(string id)
        {
            return this.GetById<PermissionEntity>(id);

        }

        /// <summary>
        /// 保存方法
        /// <param name="entity">对象</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Save(PermissionEntity entity, ref string strError)
        {
            return this.SaveOrUpdate(entity);

        }
        /// <summary>
        /// 删除方法
        /// <param name="deleteKey">主键，如果字符串请将字符串列表用单引号将字符串用上,如（'aaa','bbb'）</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Delete(string deleteKey, ref string strError)
        {
            if (!string.IsNullOrEmpty(deleteKey))
            {
                return this.Delete<PermissionEntity>(deleteKey);
            }
            return true;
        }
        /// <summary>
        /// 分页查询方法
        /// <param name="grid">分页查询的相关参数</param>
        /// </summary>
        public LigerGrid ForGrid(LigerGrid grid)
        {
            ICriterion criter = Expression.Eq("IsDeleted", false);
            if (!string.IsNullOrEmpty(grid.keyWord))
            {
                criter = Expression.And(criter,

                           Expression.Like(new string[] {
                                PermissionEntity._PrimaryKeyName ,
                           }, grid.keyWord)
                           );
            }
            return this.Query<PermissionEntity>(grid, criter);

        }
        #endregion

        #region 扩展方法
        public List<PermissionEntity> GetPermissionById(string resourceid, PermissionType permissionType = PermissionType.Role)
        {
            ICriterion criter = Expression.And( Expression.And(Expression.Eq(PermissionEntity.__IsDeleted, false),
                Expression.Eq(PermissionEntity.__ResourceId,resourceid)),
                Expression.Eq(PermissionEntity.__ResourceType,permissionType.GetHashCode())
                );
             return  this.Query<PermissionEntity>( criter);
        }

        public bool PermissionSave(string resourceId, string permissions, string unpermissions, ref string strError, PermissionType permissionType = PermissionType.Role)
        {
            if (string.IsNullOrWhiteSpace(resourceId))
            {
                strError = "参数错误，无法保存";
                return false;
            }
            ICriterion criter = Expression.And(Expression.And(Expression.Eq(PermissionEntity.__IsDeleted, false),
                Expression.Eq(PermissionEntity.__ResourceId, resourceId)),
                Expression.Eq(PermissionEntity.__ResourceType, permissionType.GetHashCode())
                );
            List<PermissionEntity> lstItem = new List<PermissionEntity>();
            if (!string.IsNullOrWhiteSpace(permissions))
            {
                foreach (var permission in permissions.Split(new char[] { ';', ',' }))
                {
                  
                    if (!string.IsNullOrWhiteSpace(permission))
                    {
                        string[] aPermission = permission.Split('|');
                        lstItem.Add(new PermissionEntity
                        {
                            ResourceId = resourceId,
                            PermissionId = Guid.NewGuid().ToString(),
                            ResourceType = permissionType.GetHashCode(),
                            PageId = aPermission[0],
                            RouteUrl = aPermission[1],
                            IsDisabled =false

                        });
                    }
                }
            }
            if (!string.IsNullOrWhiteSpace(unpermissions))
            {
                foreach (var permission in unpermissions.Split(new char[] { ';', ',' }))
                {
                  
                    if (!string.IsNullOrWhiteSpace(permission))
                    {
                        string[] aPermission = permission.Split('|');
                        lstItem.Add(new PermissionEntity
                        {
                            ResourceId = resourceId,
                            PermissionId = Guid.NewGuid().ToString(),
                            ResourceType = permissionType.GetHashCode(),
                            PageId = aPermission[0],
                            RouteUrl = aPermission[1],
                            IsDisabled =true

                        });
                    }
                }
            }
            using (var tran = this.Begin())
            {
                try
                {
                    this.Delete<PermissionEntity>(criter,false);
                    if (lstItem != null && lstItem.Count > 0)
                    {
                        this.BatchInsert<PermissionEntity>(lstItem, ref strError);
                    }
                    this.Commit();
                }
                catch (Exception ex)
                {
                    this.Rollback();
                    throw ex;
                }
            }
            return true;
        }
        #endregion

        #region  获取个人权限
        /// <summary>
        /// 获取用户权限
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public List<PermissionEntity> GetMyPermission(UserEntity entity)
        {
            StringBuilder strsql = new StringBuilder();
            string strRole = this.GetRoles(entity);
            string strGroup = this.GetGroup(entity);
            string sql = " select distinct * from " + PermissionEntity._TableName +" where 1=1 {0}";
            ICriterion criterion = Expression.Or(
                Expression.And(Expression.Eq(PermissionEntity.__ResourceId,entity.UserId), Expression.Eq(PermissionEntity.__ResourceType, PermissionType.User.GetHashCode())),
                 Expression.And(Expression.In(PermissionEntity.__ResourceId, strRole.Split(',')), Expression.Eq(PermissionEntity.__ResourceType, PermissionType.Role.GetHashCode()))
                );
            List<PermissionEntity> lstPermission = this.Query<PermissionEntity>(sql,criterion);
            return lstPermission;
        }

        /// <summary>
        /// 获取转换字符串的角色列表
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private string GetRoles(UserEntity entity)
        {
            string strRole = "";
            List<string> roleKey = new List<string>();
            if (entity.Roles != null && entity.Roles.Count > 0)
            {
                foreach (var item in entity.Roles)
                {
                    if (!roleKey.Contains(item.RoleId.ToString()))
                    {
                        strRole += (!string.IsNullOrEmpty(strRole) ? "," : "") + item.RoleId.ToString();
                        roleKey.Add(item.RoleId.ToString());
                    }
                    //if (!string.IsNullOrEmpty(item.RolePath) && item.RolePath != "0")
                    //{
                    //    string[] keys = item.RolePath.Split('_');
                    //    if (keys != null && keys.Length > 0)
                    //    {
                    //        foreach (var key in keys)
                    //        {
                    //            if (!roleKey.Contains(item.RoleId.ToString()))
                    //            {
                    //                strRole += (!string.IsNullOrEmpty(strRole) ? "," : "") + item.RoleId.ToString();
                    //                roleKey.Add(item.RoleId.ToString());
                    //            }
                    //        }
                    //    }
                    //}
                }
            }
            return strRole;
        }

        /// <summary>
        /// 获取转换字符串的角色列表
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private string GetGroup(UserEntity entity)
        {
            string strGroup = "";
            List<string> groupKey = new List<string>();
            //if (entity.Groups != null && entity.Groups.Count > 0)
            //{
            //    foreach (var item in entity.Groups)
            //    {
            //        if (!groupKey.Contains(item.GroupId.ToString()))
            //        {
            //            strGroup += (!string.IsNullOrEmpty(strGroup) ? "," : "") + item.GroupId.ToString();
            //            groupKey.Add(item.GroupId.ToString());
            //        }
            //        if (!string.IsNullOrEmpty(item.GroupPath) && item.GroupPath != "0")
            //        {
            //            string[] keys = item.GroupPath.Split('_');
            //            if (keys != null && keys.Length > 0)
            //            {
            //                foreach (var key in keys)
            //                {
            //                    if (!groupKey.Contains(item.GroupId.ToString()))
            //                    {
            //                        strGroup += (!string.IsNullOrEmpty(strGroup) ? "," : "") + item.GroupId.ToString();
            //                        groupKey.Add(item.GroupId.ToString());
            //                    }
            //                }
            //            }
            //        }
            //    }
            //}
            return strGroup;
        }
        #endregion

    }
}